home *** CD-ROM | disk | FTP | other *** search
- Path: news.compuserve.com!newsmaster
- From: 76623,2065@compuserve.com (Bobby Martin)
- Newsgroups: comp.lang.c++
- Subject: Re: Virtual Base Class
- Date: 15 Mar 1996 13:48:55 GMT
- Organization: CompuServe Incorporated
- Message-ID: <4ibsg7$ahc@dub-news-svc-3.compuserve.com>
- References: <313F98D0.102E@ucla.edu> <4i1k92$3n8@apoll.informatik.uni-bonn.de> <31472DB0.511A@ucla.edu>
- Reply-To: 76623,2065@compuserve.com (Bobby Martin)
- NNTP-Posting-Host: ad09-038.compuserve.com
- X-Newsreader: IBM NewsReader/2 v1.03
-
- >Roland Schregle wrote:
- >>
- >>
- >> I have the same problem! Somebody suggested the following (in terms of the
- >> above egg sample):
- >>
- >> void f()
- >> {
- >> a a1;
- >> d* pd = (d*)(void*)&a1;
- >> }
- >>
- >> I haven't tried this yet. C'mon you C++ cracks out there!!! :)
- >>
- >> GanjaTron
-
- This is a BAD way to try to solve this problem. If you need to cast down
- from class a to class d, you have some problem in your design. Maybe there
- should be some virtual method declared in class a that can be overloaded in
- class d to call the method in which the conversion is currently being done,
- (thus eliminating the need for the conversion since you always call it with an
- object of class d) or maybe you have a list of class a's that should be broken
- up into a list of class a's and a list of class d's.
-
- Anyway, a fairly nice solution to the problem in code is to put a dCast method
- in a, like this:
-
- class d;
-
- class a
- {
- ..
- virtual d* dCast() {return 0;}
- ..
- };
-
- (note that you'll need to put a forward reference to d (i.e. class d;) before
- your declaration of a.)
- Then redefine dCast in class d like this:
-
- class d
- {
- ..
- virtual d* dCast() {return this;}
- ..
- };
-
- then use a1->dCast() wherever you might otherwise use (d*)a1.
-
- Hope this helps!
-
- Bobby Martin
-